import { HttpClient } from '@angular/common/http';
import { Component, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { User } from './user';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {



  //对应我们登录的表单
  myForm: FormGroup;

  //输入用户名的输入控件
  userName: AbstractControl;

  //输入密码的输入控件
  password: AbstractControl;

  //观察对象
  users$!: Observable<User>
  baseUrl = 'http://127.0.0.1:/8080/user/'


  shouldShow = false;

  constructor(private fb: FormBuilder, private httpClient: HttpClient, private router: Router) {
    this.myForm = this.fb.group(
      {
        'userName': ['', Validators.compose([Validators.required, Validators.minLength(7), Validators.pattern(/^zime/)])],
        'password': ['', Validators.compose([Validators.required, Validators.minLength(6)])]
      }
    );

    this.userName = this.myForm.controls['userName'];
    this.password = this.myForm.controls['password'];
  }
  ngOnInit(): void {
    this.users$ = <Observable<User>>this.httpClient.get(this.baseUrl + 'users');
  }

  // denglushuru() {
  //   this.shouldShow = false;
  // }

  onSubmit(value: any) {
    console.log(value);
  }

  login() {
    this.httpClient.post("http://localhost:8080/user/login", this.myForm.value, { withCredentials: true }).subscribe(
      (res: any) => {
        if (res["success"] == true) {

          this.shouldShow = true
          alert("登录成功")
          this.router.navigateByUrl("home");
        } else {
          alert("用户名或密码错误！")
        }
        console.log(res)
      })
  }
}
